package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.properties.ShopProperties;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.BaiduUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.webSocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private ShopProperties shopProperties;


    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //判断收货地址异常
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        Long distance = BaiduUtil.getDistance(shopProperties.getAddress(), addressBook.getDetail());
        if (distance > 5000){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_TOO_FAR);
        }


        //判断购物车是否异常
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        //查询当前用户的购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(System.currentTimeMillis() + "");
        order.setUserId(userId);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());
        //向订单表中插入一条数据
        orderMapper.insert(order);

        //订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetailList.add(orderDetail);
        }
        //向明细表插入n条数据
        orderDetailMapper.insertBatch(orderDetailList);

        //清理购物车中的数据
        shoppingCartMapper.deleteBycurrentId(userId);

        //封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();

        //测试下单提醒
        //remind(order.getId(),order.getNumber());
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<OrdersVO> page = orderMapper.pageQuery(ordersPageQueryDTO);
        for (OrdersVO ordersVO : page) {
            List<OrderDetail> orderDetail = orderMapper.getDish(ordersVO.getId());
            String od = "";
            for (OrderDetail detail : orderDetail) {
                String dishName = detail.getName();
                od += dishName +  "  ";
            }
            log.info(od);
            ordersVO.setOrderDishes(od);
        }
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getById(Long id) {
        OrderVO orderVO = orderMapper.getById(id);
        //查询订单菜品信息
        List<OrderDetail> orderDetail = orderMapper.getDish(id);
        String od = orderDetail.toString();
        orderVO.setOrderDishes(od);
        //订单详情
        orderVO.setOrderDetailList(orderDetail);
        return orderVO;
    }

    /**
     * 接单
     * @param id
     */
    @Override
    @Transactional
    public void orderReceiving(Long id) {
        OrderVO orderVO = orderMapper.getById(id);
        orderVO.setStatus(Orders.CONFIRMED);
        orderMapper.update(orderVO);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        OrderVO orderVO = orderMapper.getById(ordersRejectionDTO.getId());
        orderVO.setStatus(Orders.CANCELLED);
        orderVO.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        //amount实收金额
        orderVO.setAmount(new BigDecimal(0));
        orderMapper.update(orderVO);
    }

    /**
     * 派送
     * @param id
     */
    @Override
    public void delivery(Long id) {
        OrderVO orderVO = orderMapper.getById(id);
        orderVO.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orderVO);
    }

    /**
     * 取消
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        OrderVO orderVO = orderMapper.getById(ordersCancelDTO.getId());
        orderVO.setStatus(Orders.CANCELLED);
        orderVO.setCancelReason(ordersCancelDTO.getCancelReason());
        orderVO.setCancelTime(LocalDateTime.now());
        //amount实收金额
        orderVO.setAmount(new BigDecimal(0));
        orderMapper.update(orderVO);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        OrderVO orderVO = orderMapper.getById(id);
        orderVO.setStatus(Orders.COMPLETED);
        orderVO.setDeliveryTime(LocalDateTime.now());
        orderVO.setCheckoutTime(LocalDateTime.now());
        orderMapper.update(orderVO);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(orderMapper.getCount(Orders.CONFIRMED));
        orderStatisticsVO.setDeliveryInProgress(orderMapper.getCount(Orders.DELIVERY_IN_PROGRESS));
        orderStatisticsVO.setToBeConfirmed(orderMapper.getCount(Orders.TO_BE_CONFIRMED));
        return orderStatisticsVO;
    }

    /**
     * 历史订单查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<OrderVO> page = orderMapper.selectAll(BaseContext.getCurrentId());
        for (OrderVO orderVO : page) {
            List<OrderDetail> orderDetailList = orderMapper.getDish(orderVO.getId());
            orderVO.setOrderDetailList(orderDetailList);
        }
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 用户取消订单
     * @param id
     */
    @Override
    public void userCancel(Long id) {
        Integer status = orderMapper.getStatusById(id);
        if (status == Orders.CONFIRMED || status == Orders.DELIVERY_IN_PROGRESS){
            throw new OrderBusinessException(MessageConstant.RING_UP);
        }
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.CANCELLED)
                .amount(new BigDecimal(0))
                .cancelReason("用户取消")
                .cancelTime(LocalDateTime.now()).build();
        orderMapper.update(orders);
    }

    /**
     * 用户再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        OrderVO orderVO = orderMapper.getById(id);
        OrdersSubmitDTO ordersSubmitDTO = new OrdersSubmitDTO();
        BeanUtils.copyProperties(orderVO,ordersSubmitDTO);
        List<OrderDetail> orderDetails = orderMapper.getDish(id);
        for (OrderDetail detail : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(BaseContext.getCurrentId());
            BeanUtils.copyProperties(detail,shoppingCart);
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        OrderVO orders = orderMapper.getById(id);
        if (orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //催单
        Map<String , Object> map = new HashMap<>();
        map.put("type" , 2);
        map.put("orderId" , id);
        map.put("content" , "订单号：" + orders.getNumber());
        String content = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(content);
    }

    /**
     * 下单提醒测试
     * @param id
     * @param outTradeNo
     */
//    public void remind(Long id , String outTradeNo){
//        Map<String , Object> map = new HashMap<>();
//        map.put("type",1);
//        map.put("orderId" ,id);
//        map.put("content","订单号"+outTradeNo);
//        String content = JSON.toJSONString(map);
//        webSocketServer.sendToAllClient(content);
//    }
}
